package com.by.controller;

import cn.hutool.core.bean.BeanUtil;
import com.by.bean.Dept;
import com.by.bean.Employee;
import com.by.common.bean.PageBean;
import com.by.common.bean.ResultBean;
import com.by.common.controller.BaseController;
import com.by.common.group.ISave;
import com.by.common.group.IUpdate;
import com.by.query.EmployeeQuery;
import com.by.service.EmployeeService;
import com.by.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@RestController
@Api(tags = "员工管理")
@RequestMapping("/v1")
public class EmployeeController extends BaseController {

    @Autowired
    EmployeeService employeeService;
    @Autowired
    private UserService userService;

    @ApiOperation("保存员工")
    @PostMapping("/employee")
    public ResultBean save(@Validated(ISave.class) @RequestBody Employee employee, BindingResult result) {
        validate(result);
        int rs = userService.queryUserAccount(employee.getUser().getAccount());
        if (rs == 1){
            return fail("该账号已存在!");
        }
        rs = employeeService.save(employee);
        return saveResult(rs);
    }

    @ApiOperation("员工列表")
    @PostMapping("/employee/query")
    public ResultBean query(@RequestBody EmployeeQuery query) {
        Map map = BeanUtil.beanToMap(query);
        PageBean bean = employeeService.query(map);
        return success("员工列表", bean);
    }

    @ApiOperation("修改员工")
    @PutMapping("/employee")
    @Transactional
    public ResultBean update(@Validated(IUpdate.class) @RequestBody Employee employee, BindingResult result) {
        validate(result);
        int rs = employeeService.update(employee);
        int rs1 = userService.update(employee.getUser());
        return updateResult(rs,rs1);
    }

    @ApiImplicitParam(name = "id", value = "员工id", dataTypeClass = Integer.class, required = true, paramType = "query",example = "1")
    @ApiOperation("删除员工")
    @DeleteMapping("/employee")
    @Transactional
    public ResultBean delete(@RequestParam(name = "id", required = true, defaultValue = "0") int id) {
        int rs = employeeService.delete(id);
        int rs1 = userService.delete(id);
        return deleteResult(rs,rs1);
    }

}
